package com.open.party.cloud.view

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.android.x.model.AppVersionEntity
import cn.android.x.model.data.ResultInfo
import com.bumptech.glide.Glide
import com.king.app.dialog.AppDialog
import com.king.app.dialog.AppDialogConfig
import com.king.app.updater.AppUpdater
import com.open.party.cloud.R
import com.open.party.cloud.model.MineCountBean
import com.open.party.cloud.model.data.LocalCache
import com.open.party.cloud.view.comm.MineMainBaseFragment
import com.open.party.cloud.view.examine.ExamineMainActivity
import com.open.party.cloud.view.freePhoto.FreePhotosMainActivity
import com.open.party.cloud.view.home.dangWuMiShu.DwmsYiJIanJianYiActivity
import com.open.party.cloud.view.home.dangYuanJiaoYu.YunKeTangStudyRecordListActivity
import com.open.party.cloud.view.home.jiCengDangJian.partyService.ZyzHuoDongListForMeActivity
import com.open.party.cloud.view.jiFen.JiFenListForMeActivity
import com.open.party.cloud.view.login.LoginActivity
import com.open.party.cloud.view.login.PwdChangeActivity
import com.open.party.cloud.view.mine.AppDownloadMainActivity
import com.open.party.cloud.view.mine.UserEditActivity
import com.open.party.cloud.view.msg.MsgForMeListActivity
import com.open.party.cloud.view.task.TaskListForMeActivity
import com.open.party.cloud.viewModel.BaseViewModel
import com.open.party.cloud.viewModel.BizViewModel
import com.open.party.cloud.viewModel.StudyViewModel
import com.sinothk.android.utils.XUtils
import com.sinothk.view.xrefresh.XRefreshLayout
import com.sinothk.view.xrefresh.listener.RefreshHandler
import kotlinx.android.synthetic.main.mine_fragment_main.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

open class MineMainFragment : MineMainBaseFragment(), View.OnClickListener {
    private var viewModel: BizViewModel? = null
    private var studyViewModel: StudyViewModel? = null

    private var currView: View? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (currView == null) {
            currView = inflater.inflate(R.layout.mine_fragment_main, container, false)
        }
        return currView
    }

    override fun updateAvatarView(filePath: String) {
        Glide.with(requireContext()).load(XUtils.string().getNotNullValue(filePath))
            .placeholder(R.drawable.default_img)
            .error(R.drawable.default_img)
            .into(avatarIv)

        Thread {
            val userInfo = LocalCache.getLoginUser()
            if (userInfo != null && XUtils.string().isNotEmpty(filePath)) {
                userInfo.photo = filePath
                LocalCache.setLoginUser(userInfo)
            }

        }.start()

    }

    private fun unLoginStatus() {

        userNameTv.text = "未登录"
        phoneNumTv.text = "—"
        avatarIv.setImageResource(R.drawable.default_img)
        refreshLayout.setRefreshEnable(false)
        userNameIv.visibility = View.INVISIBLE

        myTaskTv.text = "0"
        myExamCountTv.text = "0"
        myNoticeTv.text = "0"
        myJiFenTv.text = "0"

        exitItem.visibility = View.GONE
    }

    private fun loginStatus() {

        val userInfo = LocalCache.getLoginUser() ?: return
        userNameIv.visibility = View.VISIBLE

        userNameTv.text = XUtils.string().getNotNullValue(userInfo.name)
        phoneNumTv.text = XUtils.string().getNotNullValue(userInfo.mainmobile)
        updateAvatarView(userInfo.photo)

        refreshLayout.setRefreshEnable(true)
        refreshLayout.setRefreshHandler(object : RefreshHandler {
            override fun onLoadMore(refresh: XRefreshLayout?) {
            }

            override fun onRefresh(refresh: XRefreshLayout?) {
                Handler().postDelayed({
                    loadMineData()
                }, 500)
            }
        })

        exitItem.visibility = View.VISIBLE

        loadMineData()
    }

    private fun loadMineData() {
        viewModel!!.getMineViewData()
        studyViewModel!!.getLearningRecordClassHours()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel = BizViewModel()
        studyViewModel = StudyViewModel()
        baseViewModel = BaseViewModel()

        initView()
        setListener()
    }

    @SuppressLint("SetTextI18n")
    private fun initView() {
        versionTv.text = "V ${XUtils.app().appVersionName}"

        val versionInfo = LocalCache.getAppVersion()
        if (versionInfo != null) {
            if (versionInfo.verNumber > XUtils.app().appVersionCode) {
                newVersionTv.visibility = View.VISIBLE
            } else {
                newVersionTv.visibility = View.GONE
            }
        }
    }

    private fun setListener() {
        userInfo.setOnClickListener(this)
        avatarIv.setOnClickListener(this)
        appUpdateItem.setOnClickListener(this)
        exitItem.setOnClickListener(this)
        myTaskItem.setOnClickListener(this)
        myExamCountItem.setOnClickListener(this)
        myNoticeItem.setOnClickListener(this)
//        myJiFenItem.setOnClickListener(this)
        //
        myActivityItem.setOnClickListener(this)
        onlineStudyItem.setOnClickListener(this)
        feedbackItem.setOnClickListener(this)
        accountSetItem.setOnClickListener(this)
        freePhotosItem.setOnClickListener(this)
    }

    override fun onResume() {
        super.onResume()
        updateView()
    }

    private fun updateView() {
        if (LocalCache.getAutoLogin()) {
            loginStatus()
        } else {
            unLoginStatus()
        }
    }

    override fun onClick(v: View?) {

        when (v) {
            appUpdateItem -> {
//                showLoadingDialog("正在检测")
//                baseViewModel!!.getAppInfoForLastVersion("appUpdateItem")
                XUtils.intent().openActivity(activity, AppDownloadMainActivity::class.java)
                    .startInFragment(this)
                return
            }
            exitItem -> {
                LocalCache.logout()
                updateView()
                XUtils.toast().show("已进入游客环境")
//                XUtils.page().finishAll()
//                // 登录检测
//                XUtils.intent().openActivity(activity, LoginActivity::class.java)
//                    .startInFragment(this)
                return
            }

            avatarIv -> {
                if (!LocalCache.getAutoLogin()) {
                    XUtils.intent().openActivity(activity, LoginActivity::class.java)
                        .startInFragment(this)
                } else {
                    updateAvatar(activity!!)
                }
            }
        }

        // 需要登录项
        if (!LocalCache.getAutoLogin()) {
            // 登录检测
            XUtils.intent().openActivity(activity, LoginActivity::class.java)
                .startInFragment(this)
            return
        }

        when (v) {
            myTaskItem -> {
                // 游客不能用
                if ("TOURIST" == LocalCache.getLoginRole()) {
                    XUtils.toast().show("你没有权限")
                    return
                }

                XUtils.intent().openActivity(activity, TaskListForMeActivity::class.java).startInFragment(this)
            }
            myExamCountItem -> {
                XUtils.intent().openActivity(activity, ExamineMainActivity::class.java)
                    .putStringExtra("titleName", "我的班级")
                    .startInFragment(this)
            }
            myNoticeItem -> {
                XUtils.intent().openActivity(activity, MsgForMeListActivity::class.java).startInFragment(this)
            }
//            myJiFenItem -> {
//                XUtils.intent().openActivity(activity, JiFenListForMeActivity::class.java).startInFragment(this)
//            }

            onlineStudyItem -> {
                XUtils.intent().openActivity(activity, YunKeTangStudyRecordListActivity::class.java).startInFragment(this)
            }

            freePhotosItem -> {
                // 游客不能用
                if ("TOURIST" == LocalCache.getLoginRole()) {
                    XUtils.toast().show("你没有权限")
                    return
                }
                XUtils.intent().openActivity(activity, FreePhotosMainActivity::class.java).startInFragment(this)
            }

            myActivityItem -> {
                XUtils.intent().openActivity(activity, ZyzHuoDongListForMeActivity::class.java).startInFragment(this)
            }

            feedbackItem -> {
                XUtils.intent().openActivity(activity, DwmsYiJIanJianYiActivity::class.java)
                    .startInFragment(this)
            }
            accountSetItem -> {
                XUtils.intent().openActivity(activity, PwdChangeActivity::class.java)
                    .startInFragment(this)
            }
            userInfo->{
                XUtils.intent().openActivity(activity, UserEditActivity::class.java)
                    .startInFragment(this)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<MineCountBean>) {

        if ("getMineViewData" != result.eventType) {
            return
        }

        refreshLayout.refreshComplete()

        when (result.code) {
            ResultInfo.SUCCESS -> {
                showCountView(result.data)
            }
            ResultInfo.TOKEN_OVERDUE -> {
            }
            else -> {
            }
        }
    }

    private fun showCountView(data: MineCountBean?) {
        if (data == null) {
            myTaskTv.text = "0"
            myExamCountTv.text = "0"
            myNoticeTv.text = "0"
//            myJiFenTv.text = "0"
        } else {
            myTaskTv.text = data.taskCount.toString()
            myExamCountTv.text = data.examCount.toString()
            myNoticeTv.text = data.noticeCount.toString()
//            myJiFenTv.text = data.gralCount.toString()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveAppVersionEventBus(resultInfo: ResultInfo<AppVersionEntity?>) {

        if ("appUpdateItem" != resultInfo.eventType) {
            return
        }

        hideLoadingDialog()

        if (resultInfo.code == ResultInfo.SUCCESS) {
            val appVersion = resultInfo.data
            if (appVersion != null) {
                if (appVersion.verNumber > XUtils.app().appVersionCode) { //简单弹框升级
                    val config = AppDialogConfig()
                    config.setTitle("新版本升级")
                        .setOk("升级")
                        .setContent(
                            XUtils.string().getNotNullValue(appVersion.updateContent)
                        ).onClickOk = View.OnClickListener { v: View? ->
                        if (XUtils.string().isNotEmpty(appVersion.filePath)) {
                            AppUpdater.Builder()
                                .serUrl(appVersion.filePath)
                                .build(activity!!)
                                .start()
                        } else {
                            XUtils.toast().show("地址不可用")
                        }
                        AppDialog.INSTANCE.dismissDialog()
                    }
                    AppDialog.INSTANCE.showDialog(activity!!, config)
                } else {
                    XUtils.toast().show("当前已是最新版本")
                }
            }
        } else if (resultInfo.code == ResultInfo.TOKEN_OVERDUE) {
        } else {
            XUtils.toast().show(resultInfo.msg)
        }
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun getLearningRecordClassHoursCallback(result: ResultInfo<String>) {

        if ("getLearningRecordClassHours" != result.eventType) {
            return
        }

        when (result.code) {
            ResultInfo.SUCCESS -> {
                myJiFenTv.text = XUtils.string().getNotNullValue(result.data, "0")
            }
            ResultInfo.TOKEN_OVERDUE -> {
            }
            else -> {
            }
        }
    }
}